namespace EyeOpen.Webcam.Mvc
{
	using System;
	using System.ServiceModel;
	using System.ServiceModel.Activation;

	public class CustomServiceHostFactory 
		: ServiceHostFactoryBase
	{
		public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
		{
			var host =
				new ServiceHostFactory()
					.CreateServiceHost(constructorString, baseAddresses) as ServiceHost;

			var serviceType = Type.GetType(constructorString);

			var implementedContract = serviceType.GetInterfaces()[0];

			foreach (var address in baseAddresses)
			{
				host.AddServiceEndpoint(implementedContract, GetWsHttpBinding(serviceType), address);
				host.AddServiceEndpoint(implementedContract, GetBasicHttpBinding(serviceType), address);
				host.AddServiceEndpoint(implementedContract, GetWebHttpBinding(serviceType), address);
			}

			return host;
		}

		private WebHttpBinding GetWebHttpBinding(Type serviceType)
		{
			var webHttpBinding = new WebHttpBinding(WebHttpSecurityMode.None)
				{
					Name = serviceType.Name,
					MaxBufferPoolSize = int.MaxValue,
					MaxReceivedMessageSize = int.MaxValue,
					ReaderQuotas =
						{
							MaxArrayLength = int.MaxValue, 
							MaxStringContentLength = int.MaxValue, 
							MaxDepth = 32
						},
				};
			return webHttpBinding;
		}

		private BasicHttpBinding GetBasicHttpBinding(Type serviceType)
		{
			var basicHttpBinding = 
				new BasicHttpBinding(BasicHttpSecurityMode.Message)
					{
						Name = serviceType.Name,
						MaxBufferPoolSize = int.MaxValue,
						MaxReceivedMessageSize = int.MaxValue,
						ReaderQuotas = { MaxArrayLength = int.MaxValue, MaxStringContentLength = int.MaxValue, MaxDepth = 32 },
					};

			return basicHttpBinding;
		}

		private WSHttpBinding GetWsHttpBinding(Type serviceType)
		{
			var wsHttpBinding =
				new WSHttpBinding(SecurityMode.Message)
					{
						Name = serviceType.Name,
						MaxBufferPoolSize = int.MaxValue,
						MaxReceivedMessageSize = int.MaxValue,
						ReaderQuotas = { MaxArrayLength = int.MaxValue, MaxStringContentLength = int.MaxValue, MaxDepth = 32 },
					};

			return wsHttpBinding;
		}
	}
}